import oss2
from loguru import logger
from oss2.credentials import StaticCredentialsProvider
import os

# 用户上传文件时指定的前缀
upload_dir = "user-images/"

# 配置环境变量
# 在阿里云控制台查看Access Key（https://ram.console.aliyun.com/profile/access-keys）
# 环境变量配置方式参考：https://help.aliyun.com/zh/model-studio/developer-reference/configure-api-key-through-environment-variables?spm=a2c4g.11186623.help-menu-2400256.d_3_1.3d077becSWI3Ks#04beb8092b70d
access_key_id = os.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
access_key_secret = os.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
# access_token = os.getenv("ALIBABA_CLOUD_SECURITY_TOKEN")
access_token = ""

# 配置OSS相关参数
# oss_region：填写Bucket所在的地域ID，查看https://help.aliyun.com/zh/oss/user-guide/regions-and-endpoints?spm=a2c4g.11186623.help-menu-31815.d_2_0_0.2e212c521dRgaE#e583bfe5e6sme
# oss_bucket：填写Bucket名称，查看https://oss.console.aliyun.com/bucket
# todo 可修改为你的地域ID
oss_region = "cn-hangzhou"
# todo 可修改为你的bucket_name
bucket_name = "your oss bucket name"
endpoint = f'https://oss-{oss_region}.aliyuncs.com'

# 图像URL超时时间，单位秒
image_url_expires = 4800


class OssManager:
    def __init__(self):
        # 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        auth = oss2.ProviderAuth(
            StaticCredentialsProvider(
                access_key_id,
                access_key_secret,
                access_token
            )
        )
        # yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        self.bucket = oss2.Bucket(
            auth,
            endpoint,
            bucket_name,
        )

    def upload_file(self, file_name, file_content):
        """
        上传文件到oss
        """
        # 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
        full_file_name = f'{upload_dir}{file_name}'

        # 上传到OSS，并设置为公共可读
        self.bucket.put_object(full_file_name, file_content, headers={"x-oss-object-acl": "public-read"})

        # 生成临时可访问的URL，2小时有效期
        temp_url = self.bucket.sign_url('GET', full_file_name, expires=image_url_expires)
        logger.info(f'文件访问地址为：{temp_url}')
        return temp_url

